package com.market.fleamarket.controller;

import com.market.fleamarket.entity.Order;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.entity.Product;
import com.market.fleamarket.service.OrderService;
import com.market.fleamarket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @GetMapping
    public List<Order> getAllOrders(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return java.util.Collections.emptyList();
        }

        // 直接使用buyerId查询订单
        return orderService.findByBuyerId(user.getId());
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return null;
            }

            Order order = orderService.findById(id).orElse(null);
            if (order == null) {
                return null;
            }

            // 确保只有订单相关方可以查看
            boolean isBuyer = order.getBuyer() != null && order.getBuyer().getId().equals(currentUser.getId());
            boolean isSeller = order.getProduct() != null &&
                    order.getProduct().getUser() != null &&
                    order.getProduct().getUser().getId().equals(currentUser.getId());

            if (!isBuyer && !isSeller) {
                return null; // 无权限查看
            }

            // 确保买家信息完整
            if (order.getBuyer() != null) {
                User buyer = userService.findById(order.getBuyer().getId()).orElse(null);
                if (buyer != null) {
                    order.setBuyer(buyer);
                }
            }

            // 确保卖家信息完整
            if (order.getProduct() != null && order.getProduct().getUser() != null) {
                User seller = userService.findById(order.getProduct().getUser().getId()).orElse(null);
                if (seller != null && order.getProduct() != null) {
                    Product product = order.getProduct();
                    product.setUser(seller);
                    order.setProduct(product);
                }
            }

            return order;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/{id}/status")
    public Object updateOrderStatus(@PathVariable Long id,
                                    @RequestParam String status,
                                    HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "请先登录");
                return errorMap;
            }

            // 检查订单所有权（买家或卖家）
            Order order = orderService.findById(id).orElseThrow(() -> new RuntimeException("订单不存在"));

            boolean isBuyer = order.getBuyer() != null && order.getBuyer().getId().equals(user.getId());
            boolean isSeller = order.getProduct() != null &&
                    order.getProduct().getUser() != null &&
                    order.getProduct().getUser().getId().equals(user.getId());

            if (!isBuyer && !isSeller) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "您没有权限操作此订单");
                return errorMap;
            }

            // 验证状态转换是否合法
            if (isBuyer) {
                // 买家只能取消或确认收货
                if (!"cancelled".equals(status) && !"completed".equals(status)) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "买家只能取消订单或确认收货");
                    return errorMap;
                }

                // 买家只能取消待处理的订单
                if ("cancelled".equals(status) && !"pending".equals(order.getStatus())) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "只能取消待处理的订单");
                    return errorMap;
                }

                // 买家只能确认待收货的订单
                if ("completed".equals(status) && !"shipped".equals(order.getStatus())) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "只能确认待收货的订单");
                    return errorMap;
                }
            }

            if (isSeller) {
                // 卖家只能接单发货或取消
                if (!"shipped".equals(status) && !"cancelled".equals(status)) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "卖家只能接单发货或取消订单");
                    return errorMap;
                }

                // 卖家只能处理待处理的订单
                if (!"pending".equals(order.getStatus())) {
                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "只能处理待处理的订单");
                    return errorMap;
                }
            }

            return orderService.updateStatus(id, status);
        } catch (Exception e) {
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return errorMap;
        }
    }

    @DeleteMapping("/{id}")
    public Object deleteOrder(@PathVariable Long id, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "请先登录");
                return errorMap;
            }

            // 检查订单所有权（买家或卖家）
            Order order = orderService.findById(id).orElseThrow(() -> new RuntimeException("订单不存在"));

            boolean isBuyer = order.getBuyer() != null && order.getBuyer().getId().equals(user.getId());
            boolean isSeller = order.getProduct() != null &&
                    order.getProduct().getUser() != null &&
                    order.getProduct().getUser().getId().equals(user.getId());

            if (!isBuyer && !isSeller) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "您没有权限删除此订单");
                return errorMap;
            }

            // 确保删除操作在事务中完成
            orderService.deleteOrder(id);

            // 验证删除是否成功
            if (orderService.findById(id).isPresent()) {
                throw new RuntimeException("删除订单失败，请重试");
            }

            Map<String, Boolean> successMap = new HashMap<>();
            successMap.put("success", true);
            return successMap;
        } catch (Exception e) {
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return errorMap;
        }
    }

    @GetMapping("/seller")
    public Page<Order> getSellerOrders(@RequestParam(defaultValue = "0") int page,
                                       @RequestParam(defaultValue = "10") int size,
                                       HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            throw new RuntimeException("请先登录");
        }

        Pageable pageable = PageRequest.of(page, size);
        return orderService.findBySellerId(user.getId(), pageable);
    }
} 